<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/images/icons/favicon-16x16.png?v=2.8.0" type="image/png" sizes="16x16"><link rel="icon" href="/images/icons/favicon-32x32.png?v=2.8.0" type="image/png" sizes="32x32"><meta name="description" content="一、项目简介       创建一个类似微信的基于netty的http网页聊天室。                       二、项目搭建       源码地址为：聊天室netty-springboot                     三、导入基础环境        相关依赖1234567891011121314&lt;!--整合web模块--&amp;gt">
<meta property="og:type" content="article">
<meta property="og:title" content="使用netty创建http网页聊天室">
<meta property="og:url" content="https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/index.html">
<meta property="og:site_name" content="ljyxsg的技术成长录">
<meta property="og:description" content="一、项目简介       创建一个类似微信的基于netty的http网页聊天室。                       二、项目搭建       源码地址为：聊天室netty-springboot                     三、导入基础环境        相关依赖1234567891011121314&lt;!--整合web模块--&amp;gt">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/%E8%81%8A%E5%A4%A9%E5%AE%A4%E6%88%AA%E5%9B%BE.netty1.png">
<meta property="article:published_time" content="2023-02-09T02:19:04.000Z">
<meta property="article:modified_time" content="2023-02-10T02:44:16.286Z">
<meta property="article:author" content="ljyxsg">
<meta property="article:tag" content="ljyxsg的技术成长录">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/%E8%81%8A%E5%A4%A9%E5%AE%A4%E6%88%AA%E5%9B%BE.netty1.png"><title>使用netty创建http网页聊天室 | ljyxsg的技术成长录</title><link ref="canonical" href="https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/css/index.css?v=2.8.0"><link rel="stylesheet" href="css/custom.css"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/',
  algolia: undefined,
  assistSearch: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":false},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"light","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 6.3.0"></head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/categories/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/tags/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/about/"><span class="header-nav-menu-item__icon"><i class="fas fa-address-card"></i></span><span class="header-nav-menu-item__text">关于</span></a></div></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">ljyxsg的技术成长录</div><div class="header-banner-info__subtitle">亿点点nice的ljy</div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">使用netty创建http网页聊天室</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2023-02-09</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2023-02-10</span></span></div></header><div class="post-body">
        <h2 id="一、项目简介"   >
          <a href="#一、项目简介" class="heading-link"><i class="fas fa-link"></i></a><a href="#一、项目简介" class="headerlink" title="一、项目简介"></a>一、项目简介</h2>
      <pre><code>创建一个类似微信的基于netty的http网页聊天室。
</code></pre>
<img src="/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/%E8%81%8A%E5%A4%A9%E5%AE%A4%E6%88%AA%E5%9B%BE.netty1.png" class="" title="聊天室截图.netty1">

        <h2 id="二、项目搭建"   >
          <a href="#二、项目搭建" class="heading-link"><i class="fas fa-link"></i></a><a href="#二、项目搭建" class="headerlink" title="二、项目搭建"></a>二、项目搭建</h2>
      <p>源码地址为：<span class="exturl"><a class="exturl__link"   target="_blank" rel="noopener" href="https://gitee.com/lou_jianyang/netty-springboot" >聊天室netty-springboot</a><span class="exturl__icon"><i class="fas fa-external-link-alt"></i></span></span></p>

        <h2 id="三、导入基础环境"   >
          <a href="#三、导入基础环境" class="heading-link"><i class="fas fa-link"></i></a><a href="#三、导入基础环境" class="headerlink" title="三、导入基础环境"></a>三、导入基础环境</h2>
      <ol>
<li>相关依赖<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--整合web模块--&gt;  </span><br><span class="line">&lt;dependency&gt;  </span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  </span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;  </span><br><span class="line">&lt;/dependency&gt;  </span><br><span class="line">&lt;!--整合模板引擎 --&gt;  </span><br><span class="line">&lt;dependency&gt;  </span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;  </span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;  </span><br><span class="line">&lt;/dependency&gt;  </span><br><span class="line">&lt;dependency&gt;  </span><br><span class="line">    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;  </span><br><span class="line">    &lt;artifactId&gt;lombok&lt;/artifactId&gt;  </span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></div></figure></li>
<li>静态资源</li>
<li>yaml配置<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">server:  </span><br><span class="line">  port: 8080  </span><br><span class="line">resources:  </span><br><span class="line">  static-locations:  </span><br><span class="line">    - classpath:/static/  </span><br><span class="line">spring:  </span><br><span class="line">  thymeleaf:  </span><br><span class="line">    cache: false  </span><br><span class="line">    checktemplatelocation: true  </span><br><span class="line">    enabled: true  </span><br><span class="line">    encoding: UTF-8  </span><br><span class="line">    mode: HTML5  </span><br><span class="line">    prefix: classpath:/templates/  </span><br><span class="line">    suffix: .html</span><br></pre></td></tr></table></div></figure></li>
</ol>

        <h2 id="四、服务端开发"   >
          <a href="#四、服务端开发" class="heading-link"><i class="fas fa-link"></i></a><a href="#四、服务端开发" class="headerlink" title="四、服务端开发"></a>四、服务端开发</h2>
      <ol>
<li>添加Netty依赖<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--引入netty依赖 --&gt;  </span><br><span class="line">&lt;dependency&gt;  </span><br><span class="line">    &lt;groupId&gt;io.netty&lt;/groupId&gt;  </span><br><span class="line">    &lt;artifactId&gt;netty-all&lt;/artifactId&gt;  </span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></div></figure></li>
<li>Netty相关配置<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">netty:  </span><br><span class="line">  port: 8081  </span><br><span class="line">  path: /chat1</span><br></pre></td></tr></table></div></figure></li>
<li>Netty配置类<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">package com.ljy.config;  </span><br><span class="line">  </span><br><span class="line">import lombok.Data;  </span><br><span class="line">import org.springframework.boot.context.properties.ConfigurationProperties;  </span><br><span class="line">import org.springframework.stereotype.Component;  </span><br><span class="line">  </span><br><span class="line">@Component  </span><br><span class="line">@ConfigurationProperties(prefix = &quot;netty&quot;)  </span><br><span class="line">@Data  </span><br><span class="line">public class NettyConfig &#123;  </span><br><span class="line">  </span><br><span class="line">    private int port;//netty监听的端口  </span><br><span class="line">  </span><br><span class="line">    private String path;//websocket访问路径  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure></li>
<li>NettyWebSocketServer开发<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">package com.ljy.netty;  </span><br><span class="line">  </span><br><span class="line">import com.ljy.config.NettyConfig;  </span><br><span class="line">import io.netty.bootstrap.ServerBootstrap;  </span><br><span class="line">import io.netty.channel.ChannelFuture;  </span><br><span class="line">import io.netty.channel.EventLoopGroup;  </span><br><span class="line">import io.netty.channel.nio.NioEventLoopGroup;  </span><br><span class="line">import io.netty.channel.socket.nio.NioServerSocketChannel;  </span><br><span class="line">import io.netty.handler.logging.LogLevel;  </span><br><span class="line">import io.netty.handler.logging.LoggingHandler;  </span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;  </span><br><span class="line">import org.springframework.stereotype.Component;  </span><br><span class="line">  </span><br><span class="line">import javax.annotation.PreDestroy;  </span><br><span class="line">  </span><br><span class="line">/**  </span><br><span class="line"> * Netty服务器  </span><br><span class="line"> */  </span><br><span class="line">@Component  </span><br><span class="line">public class NettyWebSocketServer implements Runnable &#123;  </span><br><span class="line">  </span><br><span class="line">    @Autowired  </span><br><span class="line">    NettyConfig nettyConfig;  </span><br><span class="line">  </span><br><span class="line">    @Autowired  </span><br><span class="line">    WebSocketChannelInit webSocketChannelInit;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);  </span><br><span class="line">  </span><br><span class="line">    private EventLoopGroup workerGroup = new NioEventLoopGroup();  </span><br><span class="line">  </span><br><span class="line">    /**  </span><br><span class="line">     * 资源关闭--在容器销毁是关闭  </span><br><span class="line">     */  </span><br><span class="line">    @PreDestroy  </span><br><span class="line">    public void close() &#123;  </span><br><span class="line">        bossGroup.shutdownGracefully();  </span><br><span class="line">        workerGroup.shutdownGracefully();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void run() &#123;  </span><br><span class="line">        try &#123;  </span><br><span class="line">            //1.创建服务端启动助手  </span><br><span class="line">            ServerBootstrap serverBootstrap = new ServerBootstrap();  </span><br><span class="line">            //2.设置线程组  </span><br><span class="line">            serverBootstrap.group(bossGroup, workerGroup);  </span><br><span class="line">            //3.设置参数  </span><br><span class="line">            serverBootstrap.channel(NioServerSocketChannel.class)  </span><br><span class="line">                    .handler(new LoggingHandler(LogLevel.DEBUG))  </span><br><span class="line">                    .childHandler(webSocketChannelInit);  </span><br><span class="line">            //4.启动  </span><br><span class="line">            ChannelFuture channelFuture = serverBootstrap.bind(nettyConfig.getPort()).sync();  </span><br><span class="line">            System.out.println(&quot;--Netty服务端启动成功---&quot;);  </span><br><span class="line">            channelFuture.channel().closeFuture().sync();  </span><br><span class="line">        &#125; catch (Exception e) &#123;  </span><br><span class="line">            e.printStackTrace();  </span><br><span class="line">            bossGroup.shutdownGracefully();  </span><br><span class="line">            workerGroup.shutdownGracefully();  </span><br><span class="line">        &#125; finally &#123;  </span><br><span class="line">            bossGroup.shutdownGracefully();  </span><br><span class="line">            workerGroup.shutdownGracefully();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure></li>
<li>通道初始化对象<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">package com.ljy.netty;  </span><br><span class="line">  </span><br><span class="line">import com.ljy.config.NettyConfig;  </span><br><span class="line">import io.netty.channel.Channel;  </span><br><span class="line">import io.netty.channel.ChannelInitializer;  </span><br><span class="line">import io.netty.channel.ChannelPipeline;  </span><br><span class="line">import io.netty.handler.codec.http.HttpObjectAggregator;  </span><br><span class="line">import io.netty.handler.codec.http.HttpServerCodec;  </span><br><span class="line">import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;  </span><br><span class="line">import io.netty.handler.stream.ChunkedWriteHandler;  </span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;  </span><br><span class="line">import org.springframework.stereotype.Component;  </span><br><span class="line">  </span><br><span class="line">/**  </span><br><span class="line"> * 通道初始化对象  </span><br><span class="line"> */  </span><br><span class="line">@Component  </span><br><span class="line">public class WebSocketChannelInit extends ChannelInitializer &#123;  </span><br><span class="line">  </span><br><span class="line">    @Autowired  </span><br><span class="line">    NettyConfig nettyConfig;  </span><br><span class="line">  </span><br><span class="line">    @Autowired  </span><br><span class="line">    WebSocketHandler webSocketHandler;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void initChannel(Channel channel) throws Exception &#123;  </span><br><span class="line">        ChannelPipeline pipeline = channel.pipeline();  </span><br><span class="line">        //对http协议的支持.  </span><br><span class="line">        pipeline.addLast(new HttpServerCodec());  </span><br><span class="line">        // 对大数据流的支持  </span><br><span class="line">        pipeline.addLast(new ChunkedWriteHandler());  </span><br><span class="line">        //post请求分三部分. request line / request header / message body  </span><br><span class="line">        // HttpObjectAggregator将多个信息转化成单一的request或者response对象  </span><br><span class="line">        pipeline.addLast(new HttpObjectAggregator(8000));  </span><br><span class="line">        // 将http协议升级为ws协议. websocket的支持  </span><br><span class="line">        pipeline.addLast(new WebSocketServerProtocolHandler(nettyConfig.getPath()));  </span><br><span class="line">        // 自定义处理handler  </span><br><span class="line">        pipeline.addLast(webSocketHandler);  </span><br><span class="line">  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure></li>
<li>处理对象<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line">package com.ljy.netty;  </span><br><span class="line">  </span><br><span class="line">import io.netty.channel.Channel;  </span><br><span class="line">import io.netty.channel.ChannelHandler;  </span><br><span class="line">import io.netty.channel.ChannelHandlerContext;  </span><br><span class="line">import io.netty.channel.SimpleChannelInboundHandler;  </span><br><span class="line">import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;  </span><br><span class="line">import org.springframework.stereotype.Component;  </span><br><span class="line">  </span><br><span class="line">import java.util.ArrayList;  </span><br><span class="line">import java.util.List;  </span><br><span class="line">  </span><br><span class="line">/**  </span><br><span class="line"> * 自定义处理类  </span><br><span class="line"> * TextWebSocketFrame: websocket数据是帧的形式处理  </span><br><span class="line"> */  </span><br><span class="line">@Component  </span><br><span class="line">@ChannelHandler.Sharable //设置通道共享  </span><br><span class="line">public class WebSocketHandler extends SimpleChannelInboundHandler&lt;TextWebSocketFrame&gt; &#123;  </span><br><span class="line">  </span><br><span class="line">    public static List&lt;Channel&gt; channelList = new ArrayList&lt;&gt;();  </span><br><span class="line">  </span><br><span class="line">    /**  </span><br><span class="line">     * 通道就绪事件  </span><br><span class="line">     *  </span><br><span class="line">     * @param ctx  </span><br><span class="line">     * @throws Exception  </span><br><span class="line">     */    @Override  </span><br><span class="line">    public void channelActive(ChannelHandlerContext ctx) throws Exception &#123;  </span><br><span class="line">        Channel channel = ctx.channel();  </span><br><span class="line">        //当有新的客户端连接的时候, 将通道放入集合  </span><br><span class="line">        channelList.add(channel);  </span><br><span class="line">        System.out.println(&quot;有新的连接.&quot;);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    /**  </span><br><span class="line">     * 通道未就绪--channel下线  </span><br><span class="line">     *  </span><br><span class="line">     * @param ctx  </span><br><span class="line">     * @throws Exception  </span><br><span class="line">     */    @Override  </span><br><span class="line">    public void channelInactive(ChannelHandlerContext ctx) throws Exception &#123;  </span><br><span class="line">        Channel channel = ctx.channel();  </span><br><span class="line">        //当有客户端断开连接的时候,就移除对应的通道  </span><br><span class="line">        channelList.remove(channel);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /**  </span><br><span class="line">     * 读就绪事件  </span><br><span class="line">     *  </span><br><span class="line">     * @param ctx  </span><br><span class="line">     * @param textWebSocketFrame  </span><br><span class="line">     * @throws Exception  </span><br><span class="line">     */    @Override  </span><br><span class="line">    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception &#123;  </span><br><span class="line">        String msg = textWebSocketFrame.text();  </span><br><span class="line">        System.out.println(&quot;msg:&quot; + msg);  </span><br><span class="line">        //当前发送消息的通道, 当前发送的客户端连接  </span><br><span class="line">        Channel channel = ctx.channel();  </span><br><span class="line">        for (Channel channel1 : channelList) &#123;  </span><br><span class="line">            //排除自身通道  </span><br><span class="line">            if (channel != channel1) &#123;  </span><br><span class="line">                channel1.writeAndFlush(new TextWebSocketFrame(msg));  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    /**  </span><br><span class="line">     * 异常处理事件  </span><br><span class="line">     *  </span><br><span class="line">     * @param ctx  </span><br><span class="line">     * @param cause  </span><br><span class="line">     * @throws Exception  </span><br><span class="line">     */    @Override  </span><br><span class="line">    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception &#123;  </span><br><span class="line">        cause.printStackTrace();  </span><br><span class="line">        Channel channel = ctx.channel();  </span><br><span class="line">        //移除集合  </span><br><span class="line">        channelList.remove(channel);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure></li>
<li>启动类<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">package com.ljy;  </span><br><span class="line">  </span><br><span class="line">import com.ljy.netty.NettyWebSocketServer;  </span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;  </span><br><span class="line">import org.springframework.boot.CommandLineRunner;  </span><br><span class="line">import org.springframework.boot.SpringApplication;  </span><br><span class="line">import org.springframework.boot.autoconfigure.SpringBootApplication;  </span><br><span class="line">  </span><br><span class="line">@SpringBootApplication  </span><br><span class="line">public class NettySpringbootApplication implements CommandLineRunner &#123;  </span><br><span class="line">  </span><br><span class="line">    @Autowired  </span><br><span class="line">    NettyWebSocketServer nettyWebSocketServer;  </span><br><span class="line">  </span><br><span class="line">    public static void main(String[] args) &#123;  </span><br><span class="line">        SpringApplication.run(NettySpringbootApplication.class, args);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    @Override  </span><br><span class="line">    public void run(String... args) throws Exception &#123;  </span><br><span class="line">        new Thread(nettyWebSocketServer).start();  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure></li>
<li>前端js开发<figure class="highlight plaintext"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line">$(function () &#123;  </span><br><span class="line">    //这里需要注意的是，prompt有两个参数，前面是提示的话，后面是当对话框出来后，在对话框里的默认值  </span><br><span class="line">    var username = &quot;&quot;;  </span><br><span class="line">    while (true) &#123;  </span><br><span class="line">        //弹出一个输入框，输入一段文字，可以提交  </span><br><span class="line">        username = prompt(&quot;请输入您的名字&quot;, &quot;&quot;); //将输入的内容赋给变量 name ，  </span><br><span class="line">        if (username.trim() === &quot;&quot;)//如果返回的有内容  </span><br><span class="line">        &#123;  </span><br><span class="line">            alert(&quot;名称不能输入空&quot;)  </span><br><span class="line">        &#125; else &#123;  </span><br><span class="line">            $(&quot;#username&quot;).text(username);  </span><br><span class="line">            break;        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    var ws = new WebSocket(&quot;ws://localhost:8081/chat1&quot;);  </span><br><span class="line">    ws.onopen = function () &#123;  </span><br><span class="line">        console.log(&quot;连接成功.&quot;)  </span><br><span class="line">    &#125;  </span><br><span class="line">    ws.onmessage = function (evt) &#123;  </span><br><span class="line">        showMessage(evt.data);  </span><br><span class="line">    &#125;  </span><br><span class="line">    ws.onclose = function ()&#123;  </span><br><span class="line">        console.log(&quot;连接关闭&quot;)  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    ws.onerror = function ()&#123;  </span><br><span class="line">        console.log(&quot;连接异常&quot;)  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    function showMessage(message) &#123;  </span><br><span class="line">        // 张三:你好  </span><br><span class="line">        var str = message.split(&quot;:&quot;);  </span><br><span class="line">        $(&quot;#msg_list&quot;).append(`&lt;li class=&quot;active&quot;&#125;&gt;  </span><br><span class="line">                                  &lt;div class=&quot;main&quot;&gt;                                    &lt;img class=&quot;avatar&quot; width=&quot;30&quot; height=&quot;30&quot; src=&quot;/img/user.png&quot;&gt;                                    &lt;div&gt;                                        &lt;div class=&quot;user_name&quot;&gt;$&#123;str[0]&#125;&lt;/div&gt;  </span><br><span class="line">                                        &lt;div class=&quot;text&quot;&gt;$&#123;str[1]&#125;&lt;/div&gt;  </span><br><span class="line">                                    &lt;/div&gt;                                   &lt;/div&gt;  </span><br><span class="line">                              &lt;/li&gt;`);  </span><br><span class="line">        // 置底  </span><br><span class="line">        setBottom();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    $(&#x27;#my_test&#x27;).bind(&#123;  </span><br><span class="line">        focus: function (event) &#123;  </span><br><span class="line">            event.stopPropagation()  </span><br><span class="line">            $(&#x27;#my_test&#x27;).val(&#x27;&#x27;);  </span><br><span class="line">            $(&#x27;.arrow_box&#x27;).hide()  </span><br><span class="line">        &#125;,  </span><br><span class="line">        keydown: function (event) &#123;  </span><br><span class="line">            event.stopPropagation()  </span><br><span class="line">            if (event.keyCode === 13) &#123;  </span><br><span class="line">                if ($(&#x27;#my_test&#x27;).val().trim() === &#x27;&#x27;) &#123;  </span><br><span class="line">                    this.blur()  </span><br><span class="line">                    $(&#x27;.arrow_box&#x27;).show()  </span><br><span class="line">                    setTimeout(() =&gt; &#123;  </span><br><span class="line">                        this.focus()  </span><br><span class="line">                    &#125;, 1000)  </span><br><span class="line">                &#125; else &#123;  </span><br><span class="line">                    $(&#x27;.arrow_box&#x27;).hide()  </span><br><span class="line">                    //发送消息  </span><br><span class="line">                    sendMsg();  </span><br><span class="line">                    this.blur()  </span><br><span class="line">                    setTimeout(() =&gt; &#123;  </span><br><span class="line">                        this.focus()  </span><br><span class="line">                    &#125;)  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;);  </span><br><span class="line">    $(&#x27;#send&#x27;).on(&#x27;click&#x27;, function (event) &#123;  </span><br><span class="line">        event.stopPropagation()  </span><br><span class="line">        if ($(&#x27;#my_test&#x27;).val().trim() === &#x27;&#x27;) &#123;  </span><br><span class="line">            $(&#x27;.arrow_box&#x27;).show()  </span><br><span class="line">        &#125; else &#123;  </span><br><span class="line">            sendMsg();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;)  </span><br><span class="line">  </span><br><span class="line">    function sendMsg() &#123;  </span><br><span class="line">        var message = $(&quot;#my_test&quot;).val();  </span><br><span class="line">        $(&quot;#msg_list&quot;).append(`&lt;li class=&quot;active&quot;&#125;&gt;  </span><br><span class="line">                                  &lt;div class=&quot;main self&quot;&gt;                                      &lt;div class=&quot;text&quot;&gt;` + message + `&lt;/div&gt;  </span><br><span class="line">                                  &lt;/div&gt;                              &lt;/li&gt;`);  </span><br><span class="line">        $(&quot;#my_test&quot;).val(&#x27;&#x27;);  </span><br><span class="line">  </span><br><span class="line">        //发送消息  </span><br><span class="line">        message = username + &quot;:&quot; + message;  </span><br><span class="line">        ws.send(message);  </span><br><span class="line">        // 置底  </span><br><span class="line">        setBottom();  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    // 置底  </span><br><span class="line">    function setBottom() &#123;  </span><br><span class="line">        // 发送消息后滚动到底部  </span><br><span class="line">        const container = $(&#x27;.m-message&#x27;)  </span><br><span class="line">        const scroll = $(&#x27;#msg_list&#x27;)  </span><br><span class="line">        container.animate(&#123;  </span><br><span class="line">            scrollTop: scroll[0].scrollHeight - container[0].clientHeight + container.scrollTop() + 100  </span><br><span class="line">        &#125;);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></div></figure></li>
</ol>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://lou_jianyang.gitee.io">ljyxsg</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/">https://lou_jianyang.gitee.io/2023/02/09/%E4%BD%BF%E7%94%A8netty%E5%88%9B%E5%BB%BAhttp%E7%BD%91%E9%A1%B5%E8%81%8A%E5%A4%A9%E5%AE%A4/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/2023/02/10/%E6%B2%9F%E9%80%9A%E4%B8%8E%E8%A1%A8%E8%BE%BE%E5%8A%9B/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">沟通与表达力</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/2023/02/07/datax%E6%89%A7%E8%A1%8C%E6%95%B0%E9%87%87%E4%BB%BB%E5%8A%A1%E7%A4%BA%E4%BE%8B/"><span class="paginator-prev__text">datax执行数采任务示例</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E9%A1%B9%E7%9B%AE%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">
          一、项目简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA"><span class="toc-number">2.</span> <span class="toc-text">
          二、项目搭建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%AF%BC%E5%85%A5%E5%9F%BA%E7%A1%80%E7%8E%AF%E5%A2%83"><span class="toc-number">3.</span> <span class="toc-text">
          三、导入基础环境</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%BC%80%E5%8F%91"><span class="toc-number">4.</span> <span class="toc-text">
          四、服务端开发</span></a></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="/images/icons/stun-logo.svg" alt="avatar"></div><p class="sidebar-ov-author__text">Hello Stun</p></div><div class="sidebar-ov-state"><a class="sidebar-ov-state-item sidebar-ov-state-item--posts" href="/archives/"><div class="sidebar-ov-state-item__count">15</div><div class="sidebar-ov-state-item__name">归档</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--categories" href="/categories/"><div class="sidebar-ov-state-item__count">9</div><div class="sidebar-ov-state-item__name">分类</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--tags" href="/tags/"><div class="sidebar-ov-state-item__count">2</div><div class="sidebar-ov-state-item__name">标签</div></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">你已阅读了 </span><span class="sidebar-reading-info__num">0</span><span class="sidebar-reading-info__perc">%</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2023</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>ljyxsg</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v6.3.0</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.8.0</span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script src="/js/utils.js?v=2.8.0"></script><script src="/js/stun-boot.js?v=2.8.0"></script><script src="/js/scroll.js?v=2.8.0"></script><script src="/js/header.js?v=2.8.0"></script><script src="/js/sidebar.js?v=2.8.0"></script></body></html>